<template>
	<view class="goods-details">
		<!-- 顶部导航 -->
		<u-navbar id="navbar" :border-bottom="false"
			:background="{ background: 'rgba(256,256,256, '+ navStyle.backgroundBg +')', }"
			:back-bg="'rgba(0,0,0,' + navStyle.backBg + ')'" :back-icon-color="navStyle.backColor" :immersive="true">
			
			<tabs sticky-bg-color="transparent" 
				v-if="navStyle.backgroundBg > 0.1" 
				:show-bar="true" 
				:bar-width="60"
				:is-scroll="false" 
				:current="active" 
				bg-color="transparent"
				:style="{width: '100%', opacity: navStyle.backgroundBg}" 
				@change="changeActive"
				:config="{activeColor: '#24A3FF', underLineColor: '#24A3FF'}">
				<tab title="商品"></tab>
				<tab title="评价"></tab>
				<tab title="详情"></tab>
			</tabs>
		</u-navbar>
		
		<loading-view v-if="isFirstLoading"></loading-view>
        
		<view class="contain" v-if="!isNull" id="goods">
			<bubble-tips :top="90 + navHeight + 'rpx'"></bubble-tips>
			<product-swiper :imgUrls="swiperList" :video="goodsDetail.video"></product-swiper>
            
            <!-- 商品基础信息 -->
			<view class="goods-info bg-white">
                <!-- 价格 & 分享 -->
				<view class="info-header row">
					<view class="price row flex1">
						<view class="ornament mr10">
							<price-format 
                              color="#FF2C3C" 
                              :first-size="46" 
                              :second-size="32" 
                              :subscript-size="32" 
                              :price="price"
							  :weight="500" 
                            />
                            <text class="lg">/天</text>
						</view>
						<!-- <view class="muted md"> -->
                            <!-- 约¥567/月 -->
							<!-- <price-format :price="checkedGoods.market_price || goodsDetail.market_price" /> -->
						<!-- </view> -->
					</view>
					<image class="icon-share" src="/static/images/icon_share.png" @tap="showShareBtn = true"></image>
				</view>
                
                <!-- Tag -->
                <view class="row mt10 ml20">
                    <template v-if="goodsDetail.tag">
                        <view class="goods-tag">{{ goodsDetail.tag }}</view>
                    </template>
<!--                    <template v-if="item.free_shipping_type == 1">
                        <view class="goods-tag">包邮</view>
                    </template> -->
                </view>
				
                <!-- 商品名称 -->
				<view class="name lg bold">{{ goodsDetail.name }}</view>
                
                <!-- Tips -->
                <view class="lease-tips">租满三个月可买断，可提前还机</view>
			</view>
 
            <!-- 评价 -->
			<view class="evaluation bg-white mt20" id="evaluation">
				<navigator hover-class="none" :url="'/bundle/pages/lease_goods_comments/lease_goods_comments?id=' + goodsDetail.id" class="title row-between">
					<view>
						<text class="balck md mr10">用户评价</text>
						<text class="ornament sm">好评率{{ commentPercent || '0%' }}</text>
					</view>
					<view class="row">
						<text class="lighter">查看全部</text>
						<image class="icon-sm" src="/static/images/arrow_right.png" />
					</view>
				</navigator>
<!-- 				<view class="con" v-if="comment.goods_rate">
					<view class="user-info row">
						<image class="avatar mr20" :src="comment.avatar" />
						<view class="user-name md mr10">{{ comment.nickname }}</view>
					</view>
					<view class="muted xs mt10">
						<text class="mr20">{{ comment.create_time }}</text>
					</view>
					<view v-if="comment.comment" class="dec mt20">{{ comment.comment }}</view>
				</view>
				<view class="con row-center muted" v-else>暂无评价</view> -->
			</view>
            <!-- 猜你喜欢 -->
			<view class="goods-like mt20 bg-white">
				<lease-goods-like :list="goodsLike" />
			</view>
            
            <!-- 详情信息 || 租赁说明 -->
			<view class="details mt20 bg-white" id="details">
                <u-tabs
                  :list="tabsList" 
                  :is-scroll="false" 
                  :current="currentTab"
                  :bold="true"
                  font-size="30rpx"
                  active-color="#24A3FF"
                  inactive-color="#333333"
                  bar-width="120"
                  bar-height="6"
                  @change="changeTab"
                /> 
                <!-- 详情内容 -->
				<view class="content">
                    <template v-if="currentTab === 0">
                        <u-parse 
                          :html="goodsDetail.content" 
                          :lazy-load="true" 
                          :show-with-animation="true" 
                        />
                    </template>
                    <template v-else-if="currentTab === 1">
                        <u-parse
                          :html="goodsDetail.lease_explain" 
                          :lazy-load="true" 
                          :show-with-animation="true" 
                        />
                    </template>
				</view>
			</view>
            
            <!-- Widget -->
			<view class="footer row bg-white fixed">
				<navigator class="btn column-center" hover-class="none" url="/bundle/pages/contact_offical/contact_offical">
					<image class="icon-md" src="/static/images/icon_contact.png" />
					<text class="xxs lighter">客服</text> 
				</navigator>
				<view class="btn column-center" @tap="collectGoodsFun">
					<image class="icon-md" :src="goodsDetail.is_collect == 1 ? '/static/images/icon_collection_s.png' : '/static/images/icon_collection.png'" />
					<text class="xxs lighter">收藏</text>
				</view>
				<view class="right-buy br60 white mr20 ml10 md" @tap="showSpecFun">立即租赁</view>
			</view>
		</view>
        <!-- 找不到商品 -->
		<view v-else>
			<view class="details-null column-center">
				<image class="img-null" src="/static/images/goods_null.png" />
				<view class="xs muted">该商品已下架或不存在，去逛逛别的吧~</view>
			</view>
			<recommend />
		</view>
        
        
        <!-- 商品规格选择Popup -->
		<lease-spec-popup 
          :show="showSpec" 
          :goods="goodsDetail" 
          buttonTxt="立即租赁" 
          @close="showSpec = false" 
		  @confirm="onConfirm" 
        />
        
        <!-- 分享Popup -->
<!-- 		<share-popup 
          :show="showShareBtn" 
          :goods-id="id"  
		  type="lease_goods"
          :img-url="goodsDetail.image" 
          :summary="goodsDetail.remark" 
          :share-title="goodsDetail.name" 
          @close="showShareBtn = false" 
        /> -->
		
		<share-popup
			:show="showShareBtn"
			@close="showShareBtn = false" 
			:share-id="id" 
			pagePath="bundle/pages/lease_goods_details/lease_goods_details" 
			:type="2" 
			:config="{
				avatar: userInfo.avatar,
				nickname: userInfo.nickname,
				image: goodsDetail.image,
				price: price,
				name: goodsDetail.name
		}">
		</share-popup>
		
	</view>
</template>

<script>
    import { 
        getLeaseGoodsDetail,
        getGoodsCoupon,
        getGoodsComment,
        leaseBuy,
        leaseCollectGoods
     } from '@/api/lease.js'
     
	import { getPoster } from '@/api/store';
	import { mapGetters } from 'vuex';
	import { toLogin } from '@/utils/login';
	import {
		strToParams,
		getRect
	} from '@/utils/tools'
    const app = getApp()
	export default {
		data() {
			return {
				isFirstLoading: true,   // 是否第一次加载
				isNull: false,          // 是否找到该商品
				showSpec: false,        // 规格选择Popup
				showShareBtn: false,    // 分享Popup
				swiperList: [],         // 轮播图列表
				goodsDetail: {},        // 商品信息数据
				goodsLike: [],          // 猜你喜欢列表数据
				goodsType: 0,           // 商品类型
				comment: {},            // 留言数据
				id: '',                 // 当前商品ID
                currentTab: 0,          // Tabs当前位置                
				commentPercent: '',		// 好评率
                // Tabs 列表
                tabsList: [
                {
                    kay: 'goods',
                    name: '商品详情'
                }, {
                    key: 'lease',
                    name: '租赁说明'
                }],
				
				navStyle: {
					backBg: 0.4,
					backgroundBg: 0,
					backColor: 'rgba(256,256,256,1)'
				},
				active: 0,
				topArr: [],
			};
		},
		
		onPageScroll(e) {
			const top = uni.upx2px(500)
			const {
				scrollTop
			} = e
			const percent = scrollTop / top
			this.navStyle.backgroundBg = percent
			this.navStyle.backBg = 0.4 * (0.5 - percent)
			this.navStyle.backColor = percent < 0.5 ? 'rgba(256,256,256,' + (0.5 - percent) * 2 + ')' : 'rgba(0,0,0,' +
				(
					percent - 0.5) * 2 + ')'
			if (!this.isTouchStart) return
			const topList = this.topArr.map((item, index) => ({
					index,
					top: item
				}))
				.filter(item => item.top <= scrollTop)
		
			if (topList.length) {
				const index = topList.sort((a, b) => b.top - a.top)[0].index
				if (this.active == index) return
				this.active = index
			}
		},
        
        computed: {
            ...mapGetters(['userInfo']),
            // 价格
            price() {
              if (!this.goodsDetail.hasOwnProperty('goods_periods')) return;
              
              const periods = this.goodsDetail.goods_periods.periods;
              const day = Math.max(...periods.map(item => item.day));
              const period = periods.find(item => item.day == day);
              const basePrice = this.goodsDetail.price;
              const price = basePrice * (period.rent / 100) / period.day * period.periods;
              
              // return price.toFixed(2);
			  return Number(price.toString().match(/^\d+(?:\.\d{0,2})?/));
            },
			
			navHeight() {
				return app.globalData.navHeight
			},
        },
        
        methods: {
			changeActive(index) {
				this.isTouchStart = false
			
				uni.pageScrollTo({
					scrollTop: this.topArr[index],
					duration: 200
				});
			},
			
			getRectInfo() {
				if (this.topArr.length) return
				getRect('#goods').then((res) => {
					this.topArr[0] = res.top - this.navHeight
				})
				getRect('#evaluation').then((res) => {
					this.topArr[1] = res.top - this.navHeight
				})
				getRect('#details').then((res) => {
					this.topArr[2] = res.top - this.navHeight
				})
			},
			
			
            // 改变当前的Tabs位置
            changeTab(index) {
                this.currentTab = index;
            },
            
            // 获取商品信息
        	getGoodsDetailFun() {
                getLeaseGoodsDetail({ id: this.id }).then(res => {
                    if (res.code == 1) {
                        const data = res.data;
                        
                        this.goodsDetail = data;
                        this.swiperList = data.goods_image;
                        this.comment = data.comment;
                        this.goodsLike = data.like;
                        
                        this.$nextTick(() => {
							
							this.isFirstLoading = false
							
							// 滚动到顶部，防止h5端出现问题
							uni.pageScrollTo({
								scrollTop: 0,
								duration: 0,
							});
							this.getRectInfo()
						});
                    } else {
                    	this.isNull = true
                    	this.isFirstLoading = false;
                    }
                });
        	},
            
            // 收藏商品
        	collectGoodsFun() {
        		if (!this.isLogin) return toLogin();
                
                const is_collect = this.goodsDetail.is_collect;
                
                leaseCollectGoods({
                	status: is_collect == 0 ? 1 : 0,
                	id: this.id
                }).then(res => {
                    if (res.code != 1) return;
                    
                    is_collect == 0 
                      ? this.$toast({ title: '收藏成功' })
                      : this.$toast({ title: '取消收藏' });
                      
                    this.getGoodsDetailFun();
                });
        	},
            
            // 展示规格
        	showSpecFun() { 
        		if (!this.isLogin) return toLogin();
        		this.showSpec = true;
        	},
            
            // 立即租赁
            onConfirm(field) {
				uni.navigateTo({
					url: '/bundle/pages/lease_confirm_order/lease_confirm_order?data=' 
				      + encodeURIComponent((JSON.stringify(field)))
				})
            },
        },
        
		onLoad(options) {
			if (options && options.scene) {
				let scene = strToParams(decodeURIComponent(options.scene));
				console.log(scene, decodeURIComponent(options.scene))
				options.id = scene.id;
			}
			
			if (!options.id) 
                return this.$toast({
					title: '缺少参数，无法查看商品'
				}, { tab: 3 });

            const goods_id = options.id || 4;
			this.id = goods_id;
            
            getGoodsComment({ lease_goods_id: goods_id }).then(({ code, data }) => {
				if (code != 1) return;
				this.commentPercent = data.percent;
            });
		},
        
		onShow() {
			this.getGoodsDetailFun();
		},
        
        // 分享
		onShareAppMessage() {
            const goodsDetail = this.goodsDetail;
            const userInfo = this.userInfo;
            
			return {
				title: goodsDetail.name,
				imageUrl: goodsDetail.image,
				path: '/pages/goods_details/goods_details?id=' 
                  + this.id 
                  + "&invite_code=" 
                  + userInfo.distribution_code
			};
		}
	};
</script>

<style lang="scss">
	.goods-details {
		padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
        
        .lease-tips {
            margin: 0 20rpx;
            padding: 10rpx 18rpx;
            border-radius: 4rpx;
            font-size: 24rpx;
            background-color: #FFFADE;
            color: #F95F2F;
        }

		.goods-info {
			position: relative;
            padding-bottom: 20rpx;

			.info-header {
				padding: 20rpx 0 0rpx 24rpx;

				.price {
					align-items: baseline;
				}
			}
            
            .goods-tag {
                padding: 8rpx 10rpx;
                margin-right: 20rpx;
                border-radius: 4px;
                font-size: 22rpx;
                background-color: rgba(36, 163, 255, 0.1);
                color: #24a3ff;
            }
            
			.vip-price {
				margin: 0 24rpx;
				background-color: #FFE9BA;
				line-height: 36rpx;
				border-radius: 6rpx;
				overflow: hidden;
				.price-name {
					background-color: #101010;
					padding: 3rpx 12rpx;
					color: #FFD4B7;
					position: relative;
					overflow: hidden;
					&::after {
						content: '';
						display: block;
						width: 20rpx;
						height: 20rpx;
						position: absolute;
						right: -15rpx;
						background-color: #FFE9BA;
						border-radius: 50%;
						top: 50%;
						transform: translateY(-50%);
						box-sizing: border-box;
					}
				}
			}
			.name {
				padding: 20rpx 24rpx;
				flex: 1;
			}

			.icon-share {
				width: 134rpx;
				height: 60rpx;
			}
		}

		.discount {
			padding: 24rpx;
			.text {
				width: 100rpx;
				flex: none;
			}

			.con {
				width: 400rpx;
			}

			.coupons-item {
				overflow: hidden;

				&>view {
					position: relative;
					height: 40rpx;
					line-height: 40rpx;
					padding: 0 18rpx;
					border-radius: 6rpx;
					box-sizing: border-box;
					background-color: $-color-ornament;
					color: #fff;
					white-space: nowrap;
					overflow: hidden;

					&::after,
					&::before {
						content: '';
						display: block;
						width: 20rpx;
						height: 20rpx;
						position: absolute;
						left: -14rpx;
						background-color: #fff;
						border-radius: 50%;
						border: 1px solid currentColor;
						box-sizing: border-box;
					}

					&::after {
						right: -14rpx;
						left: auto;
					}
				}
			}
		}

		.details-null {
			padding-top: 140rpx;
			margin-bottom: 100rpx;
		}

		.spec {
			// padding: 24rpx 24rpx;
			padding: 10rpx 24rpx;

			.text {
				width: 100rpx;
			}
		}

		.evaluation {
			.title {
				height: 100rpx;
				border-bottom: $-solid-border;
				padding: 0 24rpx;
			}

			.con {
				padding: 30rpx 24rpx;
			}

			.user-info .avatar {
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
			}
		}

		.details {
			.title {
				line-height: 88rpx;
				text-align: center;
			}

			&>.content {
				padding: 0 20rpx 20rpx;
				overflow: hidden;
				::v-deep image{
					vertical-align: middle;
				}
				// #ifdef H5
				::v-deep img{
					vertical-align: middle;
				}
				// #endif
                // #ifdef MP-WEIXIN || APP-PLUS
                ::v-deep ._img {
                    display: block;
                }
                // #endif
			}
		}

		.footer {
			height: 100rpx;
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			box-sizing: content-box;
			padding-bottom: env(safe-area-inset-bottom);

			.btn {
				width: 100rpx;
				height: 100rpx;
				position: relative;
				line-height: 1.3;
			}

			.cart-num {
				position: absolute;
				left: 60rpx;
				top: 6rpx;
			}

			.add-cart,
			.right-buy {
				flex: 1;
				text-align: center;
				padding: 16rpx 0;
			}

			.add-cart {
				background-color: rgba(36, 163, 255, 0.1);
			}

			.right-buy {
				background-color: $-color-primary;
			}
		}

		.group-play {
			.title {
				padding: 20rpx 28rpx;
				border-bottom: $-solid-border;
			}

			.steps {
				padding: 20rpx 28rpx;

				.step {
					flex: none;
				}

				.line {
					flex: 1;
					border: 1px dashed #999999;
					margin: 0 20rpx;
				}

				.number {
					border: 1rpx solid #707070;
					width: 28rpx;
					height: 28rpx;
					border-radius: 50%;
					line-height: 28rpx;
					text-align: center;
					margin-right: 6rpx;
				}
			}
		}

		.group-list {
			.group-item {
				padding: 20rpx 24rpx;

				&:not(:last-of-type) {
					border-bottom: $-solid-border;
				}

				.group-btn {
					background: linear-gradient(90deg, #f95f2f 0%, #ff2c3c 100%);
					height: 58rpx;
					padding-left: 28rpx;
					padding-right: 28rpx;
					margin-left: 30rpx;
					box-shadow: 0px 6rpx 12rpx rgba(249, 47, 138, 0.4);
				}
			}
		}
	}
</style>
